﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using MineBoxRelease.Model;
using MineBoxRelease.View;

namespace MineBoxRelease.Core.View.Creator
{
    class PlanBoxViewCreator : IViewCreator
    {
        public BaseView Create(XmlElement root)
        {
            PlanBoxView view;
            try
            {
                string tabTitle = root.GetAttribute("title");
                XmlNodeList nodes = root.GetElementsByTagName("plan");
                List<Plan> list = new List<Plan>();
                foreach (XmlNode node in nodes)
                {
                    bool isCompleted = node.Attributes["isCompleted"].InnerText.Equals("1");
                    string content = node.Attributes["content"].InnerText;
                    list.Add(new Plan() { Content = content, IsCompleted = isCompleted });
                }
                view = new PlanBoxView(tabTitle);
                view.SetList(list);
            }
            catch (Exception)
            {
                throw;
            }
            return view;
        }

        public BaseView Create(string title = null)
        {
            if (title == null || title.Equals("")) title = "计划表";
            return new PlanBoxView(title);
        }

        public void Save(BaseView view, string path)
        {
            try
            {
                PlanBoxView v = view as PlanBoxView;
                List<Plan> list = v.GetList();
                XmlTextWriter writer = new XmlTextWriter(path, Encoding.UTF8);
                writer.Formatting = Formatting.Indented;
                writer.WriteStartDocument();
                /*根节点*/
                writer.WriteStartElement("viewxml");
                writer.WriteAttributeString("title", v.Title);
                writer.WriteAttributeString("type", "PlanBox");

                foreach (Plan plan in list)
                {
                    writer.WriteStartElement("plan");
                    writer.WriteAttributeString("isCompleted", plan.IsCompleted ? "1" : "0");
                    writer.WriteAttributeString("content", plan.Content);
                    writer.WriteEndElement();
                }

                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Close();
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
